﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using ReportWizard.DataAccess;
using ReportWizard.Helpers;
using ReportWizard.Properties;

namespace ReportWizard.Forms
{
    public partial class EditBookmarksForm : IconForm
    {
        private WordTemplate CurrentWordTemplate { get; set; }

        public EditBookmarksForm(WordTemplate currentWordTemplate)
        {
            InitializeComponent();

            CurrentWordTemplate = currentWordTemplate;

            ShowCustomLeftButton = false;
            ShowCustomRightButton = false;
        }

        private void EditBookmarksFormLoad(object sender, EventArgs e)
        {
            FillBookmarks();

            HeaderText = string.Format("Редактирование шаблона {0}", CurrentWordTemplate);
        }

        private void CancelClick(object sender, EventArgs e)
        {
            Close();
        }

        private void FillContextMenu()
        {
            cmBookmarks.Items.Clear();

            ToolStripMenuItem miGroupBoomarks = new ToolStripMenuItem
            {
                Name = "miGroupBoomarks",
                Text = Resources.GroupBookmarks,
                Image = Resources.shape_move_back_icon
            };
            miGroupBoomarks.Click += GroupBoomarksClick;

            ToolStripMenuItem miUngroupBoomarks = new ToolStripMenuItem
            {
                Name = "miUngroupBoomarks",
                Text = Resources.UngroupBookmarks,
                Image = Resources.shape_move_front_icon
            };
            miUngroupBoomarks.Click += UngroupBoomarksClick;

            ToolStripMenuItem miReplaceToGroupBookmark = new ToolStripMenuItem
            {
                Text = Resources.MoveToGroup,
                Enabled = false,
                Image = Resources.shape_move_backwards_icon
            };

            cmBookmarks.Items.Add(miGroupBoomarks);
            cmBookmarks.Items.Add(miUngroupBoomarks);
            cmBookmarks.Items.Add(miReplaceToGroupBookmark);

            List<BookmarkGroup> lGroups = BookmarkGroup.SelectInTemplate(CurrentWordTemplate.Id);
            if (lGroups != null)
            {
                miReplaceToGroupBookmark.Enabled = true;

                ToolStripMenuItem[] groupItems = new ToolStripMenuItem[lGroups.Count];
                for (int i = 0; i < lGroups.Count; i++)
                {
                    groupItems[i] = new ToolStripMenuItem
                                        {
                                            Text = string.Format("{0} / ⌂ {1}", lGroups[i].Name, lGroups[i].GroupBookmarks.Count),
                                            Visible = true,
                                            Tag = lGroups[i].Id
                                        };
                    groupItems[i].Click += MoveToBoomarkGroupClick;
                }

                miReplaceToGroupBookmark.DropDownItems.AddRange(groupItems);
                cmBookmarks.Items.Add(miReplaceToGroupBookmark);
            }
        }

        private void FillBookmarks()
        {
            dgvBookmarks.AutoGenerateColumns = false;
            dgvBookmarks.DataSource = null;

            if (CurrentWordTemplate != null)
            {
                tbTemplateFileName.Text = Path.GetFileNameWithoutExtension(CurrentWordTemplate.FileName);
                tbTemplateDescription.Text = CurrentWordTemplate.Description;
                CheckFooterChecked = CurrentWordTemplate.Visible;

                List<WordBookmark> lBookmarks = WordBookmark.Select(CurrentWordTemplate.Id, true);
                if (lBookmarks != null)
                {
                    dgvBookmarks.DataSource = lBookmarks;
                }
            }

            int oldGroupId = 0;
            Color fixedColor = Color.White;
            int groupIndex = 0;

            for (int i = 0; i < dgvBookmarks.Rows.Count; i++)
            {
                bool isTextBookmark = Convert.ToBoolean(dgvBookmarks["cType", i].Value);
                int groupBookmarkId = Convert.ToInt32(dgvBookmarks["cBookmarkGroup", i].Value);

                if (!isTextBookmark)
                {
                    dgvBookmarks.Rows[i].DefaultCellStyle.BackColor = Color.NavajoWhite;
                }
                else
                {
                    if (groupBookmarkId == 0)
                    {
                        dgvBookmarks.Rows[i].DefaultCellStyle.BackColor = Color.White;
                    }
                    else
                    {
                        dgvBookmarks["cType", i].ReadOnly = true;
                        dgvBookmarks["cBookmarkGroupName", i].Value = BookmarkGroup.Select(groupBookmarkId).Name;
                        if (groupBookmarkId != oldGroupId)
                        {
                            groupIndex++;

                            Color currentColor = groupIndex % 2 == 0 ? Color.LightGray : Color.LightGoldenrodYellow;
                            dgvBookmarks.Rows[i].DefaultCellStyle.BackColor = currentColor;

                            oldGroupId = groupBookmarkId;
                            fixedColor = currentColor;
                        }
                        else
                        {
                            dgvBookmarks.Rows[i].DefaultCellStyle.BackColor = fixedColor;
                        }
                    }
                }
            }

            FillContextMenu();
        }

        private void UpdateSelectedBookmarks(int groupId)
        {
            for (int i = 0; i < dgvBookmarks.SelectedRows.Count; i++)
            {
                WordBookmark wb = new WordBookmark
                                      {
                                          Id = Convert.ToInt32(dgvBookmarks.SelectedRows[i].Cells["cId"].Value),
                                          Name = dgvBookmarks.SelectedRows[i].Cells["cName"].Value.ToString(),
                                          Description =
                                              dgvBookmarks.SelectedRows[i].Cells["cDescription"].Value != null
                                                  ? dgvBookmarks.SelectedRows[i].Cells["cDescription"].Value.
                                                        ToString()
                                                  : string.Empty,
                                          BookmarkGroupId = groupId,
                                          IsTextBookmark =
                                              Convert.ToBoolean(
                                                  dgvBookmarks.SelectedRows[i].Cells["cType"].Value),
                                          Visible = true
                                      };
                wb.Update();

                bool isGroup = groupId > 0;

                ReportBaseObject.DeleteAllInBookmark(isGroup ? wb.Id : groupId, isGroup);
            }
        }

        private void UpdateBookmarks()
        {
            for (int i = 0; i < dgvBookmarks.Rows.Count; i++)
            {
                WordBookmark wb = new WordBookmark
                                      {
                                          Id = Convert.ToInt32(dgvBookmarks["cId", i].Value),
                                          Name = dgvBookmarks["cName", i].Value.ToString(),
                                          Description =
                                              dgvBookmarks["cDescription", i].Value != null
                                                  ? dgvBookmarks["cDescription", i].Value.ToString()
                                                  : string.Empty,
                                          BookmarkGroupId = Convert.ToInt32(dgvBookmarks["cBookmarkGroup", i].Value),
                                          IsTextBookmark = Convert.ToBoolean(dgvBookmarks["cType", i].Value),
                                          Visible = true
                                      };
                wb.Update();
            }
        }

        private void SaveTemplateInfoClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbTemplateFileName.Text))
            {
                CurrentWordTemplate.FileName = string.Format("{0}.dot", Path.GetFileNameWithoutExtension(tbTemplateFileName.Text.Trim()));
                CurrentWordTemplate.Description = tbTemplateDescription.Text.Trim();
                CurrentWordTemplate.Visible = CheckFooterChecked;
                CurrentWordTemplate.Update();
            }

            UpdateBookmarks();
            Close();
        }

        private void dgvBookmarks_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //if (e.Value is Boolean)
            //{
            //    bool cellValue = Convert.ToBoolean(e.Value);
            //    dgvBookmarks.Rows[e.RowIndex].DefaultCellStyle.BackColor = cellValue ? Color.White : Color.NavajoWhite;
            //    e.FormattingApplied = true;
            //}
            
            //if (dgvBookmarks.Columns[e.ColumnIndex].Name == "cBookmarkGroup")
            //{
            //    if (e.Value.ToString().Equals(new Guid().ToString()))
            //    {
            //        dgvBookmarks.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Azure;
            //        e.FormattingApplied = true;
            //    }
            //}
        }

        private void GroupBookmarks(bool isNewGroup)
        {
            if (dgvBookmarks.SelectedRows.Count <= 1 && isNewGroup)
            {
                ShowMessage.Info(Resources.NeedMoreThenOneBookmarkForGroup);
            }
            else
            {
                bool isImageBookmarkExist = false;
                for (int i = 0; i < dgvBookmarks.SelectedRows.Count; i++)
                {
                    isImageBookmarkExist = !Convert.ToBoolean(dgvBookmarks.SelectedRows[i].Cells["cType"].Value);
                    if (isImageBookmarkExist)
                        break;
                }
                
                if (isImageBookmarkExist)
                {
                    ShowMessage.Info(Resources.NeedOnlyTextBookmarksInGroupWorkiing);
                }
                else
                {
                    if (isNewGroup)
                    {
                        SetFileNameForm sf = new SetFileNameForm(true)
                                                 {
                                                     FormCaption = Resources.CommonNameForBookmarkGroup,
                                                     Text = Resources.GrouppingBookmarks
                                                 };
                        if (sf.ShowDialog() == DialogResult.OK)
                        {
                            BookmarkGroup bg = new BookmarkGroup
                                                   {
                                                       Name = sf.NewName
                                                   };
                            bg.Insert();

                            if (bg.Id != 0)
                            {
                                UpdateBookmarks();
                                UpdateSelectedBookmarks(bg.Id);
                                FillBookmarks();
                            }
                        }
                    }
                    else
                    {
                        UpdateBookmarks();
                        UpdateSelectedBookmarks(0);
                        FillBookmarks();
                    }
                }
            }
        }

        private void MoveToBoomarkGroupClick(object sender, EventArgs e)
        {
            UpdateSelectedBookmarks(Convert.ToInt32(((ToolStripMenuItem)sender).Tag));
            FillBookmarks();
        }

        private void GroupBoomarksClick(object sender, EventArgs e)
        {
            GroupBookmarks(true);
        }

        private void UngroupBoomarksClick(object sender, EventArgs e)
        {
            GroupBookmarks(false);
        }
    }
}
